package com.factory;

import com.factory.dao.EmployeeDao;
import com.factory.entity.Employee;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

public class MainApp {
    private static SqlSessionFactory sqlSessionFactory;
    private static Scanner scanner = new Scanner(System.in);

    static {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            System.out.println("MyBatis 初始化成功！");
        } catch (Exception e) {
            System.err.println("MyBatis 初始化失败：" + e.getMessage());
        }
    }

    public static void main(String[] args) {
        System.out.println("=== 工厂员工信息管理系统 ===");

        while (true) {
            showMenu();
            int choice = getIntInput("请选择操作：");

            switch (choice) {
                case 1:
                    addEmployee();
                    break;
                case 2:
                    deleteEmployee();
                    break;
                case 3:
                    updateEmployee();
                    break;
                case 4:
                    queryEmployeeById();
                    break;
                case 5:
                    listAllEmployees();
                    break;
                case 6:
                    queryEmployeesByCondition();
                    break;
                case 7:
                    showStatistics();
                    break;
                case 0:
                    System.out.println("谢谢使用！");
                    return;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }

    private static void showMenu() {
        System.out.println("\n===== 主菜单 =====");
        System.out.println("1. 添加员工");
        System.out.println("2. 删除员工");
        System.out.println("3. 修改员工");
        System.out.println("4. 根据ID查询");
        System.out.println("5. 查询所有员工");
        System.out.println("6. 条件查询");
        System.out.println("7. 统计信息");
        System.out.println("0. 退出系统");
    }

    // 添加员工
    private static void addEmployee() {
        System.out.println("\n--- 添加员工 ---");

        Employee employee = new Employee();
        employee.setEmpName(getStringInput("姓名："));
        employee.setGender(getStringInput("性别(M/F)："));
        employee.setAge(getIntInput("年龄："));
        employee.setPosition(getStringInput("职位："));
        employee.setDepartment(getStringInput("部门："));
        employee.setSalary(getDoubleInput("薪资："));
        employee.setEmail(getStringInput("邮箱："));
        employee.setPhone(getStringInput("电话："));
        employee.setAddress(getStringInput("地址："));
        employee.setHireDate(new Date());

        try (SqlSession session = sqlSessionFactory.openSession()) {
            EmployeeDao employeeDao = session.getMapper(EmployeeDao.class);
            int result = employeeDao.insertEmployee(employee);
            session.commit();

            if (result > 0) {
                System.out.println("员工添加成功！员工ID：" + employee.getEmpId());
            } else {
                System.out.println("员工添加失败！");
            }
        } catch (Exception e) {
            System.err.println("添加员工失败：" + e.getMessage());
        }
    }

    // 删除员工
    private static void deleteEmployee() {
        System.out.println("\n--- 删除员工 ---");
        int empId = getIntInput("请输入要删除的员工ID：");

        try (SqlSession session = sqlSessionFactory.openSession()) {
            EmployeeDao employeeDao = session.getMapper(EmployeeDao.class);

            // 先查询员工是否存在
            Employee employee = employeeDao.selectEmployeeById(empId);
            if (employee == null) {
                System.out.println("员工不存在！");
                return;
            }

            System.out.println("即将删除员工：" + employee);
            String confirm = getStringInput("确认删除？(y/n)：");

            if ("y".equalsIgnoreCase(confirm)) {
                int result = employeeDao.deleteEmployee(empId);
                session.commit();

                if (result > 0) {
                    System.out.println("员工删除成功！");
                } else {
                    System.out.println("员工删除失败！");
                }
            }
        } catch (Exception e) {
            System.err.println("删除员工失败：" + e.getMessage());
        }
    }

    // 修改员工
    private static void updateEmployee() {
        System.out.println("\n--- 修改员工信息 ---");
        int empId = getIntInput("请输入要修改的员工ID：");

        try (SqlSession session = sqlSessionFactory.openSession()) {
            EmployeeDao employeeDao = session.getMapper(EmployeeDao.class);

            Employee employee = employeeDao.selectEmployeeById(empId);
            if (employee == null) {
                System.out.println("员工不存在！");
                return;
            }

            System.out.println("当前信息：" + employee);
            System.out.println("请输入新信息（直接回车保持原值）：");

            String newName = getStringInput("姓名[" + employee.getEmpName() + "]：");
            if (!newName.isEmpty()) employee.setEmpName(newName);

            String newGender = getStringInput("性别[" + employee.getGender() + "]：");
            if (!newGender.isEmpty()) employee.setGender(newGender);

            String newAge = getStringInput("年龄[" + employee.getAge() + "]：");
            if (!newAge.isEmpty()) employee.setAge(Integer.parseInt(newAge));

            String newPosition = getStringInput("职位[" + employee.getPosition() + "]：");
            if (!newPosition.isEmpty()) employee.setPosition(newPosition);

            String newDepartment = getStringInput("部门[" + employee.getDepartment() + "]：");
            if (!newDepartment.isEmpty()) employee.setDepartment(newDepartment);

            String newSalary = getStringInput("薪资[" + employee.getSalary() + "]：");
            if (!newSalary.isEmpty()) employee.setSalary(Double.parseDouble(newSalary));

            String newEmail = getStringInput("邮箱[" + employee.getEmail() + "]：");
            if (!newEmail.isEmpty()) employee.setEmail(newEmail);

            String newPhone = getStringInput("电话[" + employee.getPhone() + "]：");
            if (!newPhone.isEmpty()) employee.setPhone(newPhone);

            String newAddress = getStringInput("地址[" + employee.getAddress() + "]：");
            if (!newAddress.isEmpty()) employee.setAddress(newAddress);

            int result = employeeDao.updateEmployee(employee);
            session.commit();

            if (result > 0) {
                System.out.println("员工信息修改成功！");
            } else {
                System.out.println("员工信息修改失败！");
            }
        } catch (Exception e) {
            System.err.println("修改员工失败：" + e.getMessage());
        }
    }

    // 根据ID查询
    private static void queryEmployeeById() {
        System.out.println("\n--- 根据ID查询员工 ---");
        int empId = getIntInput("请输入员工ID：");

        try (SqlSession session = sqlSessionFactory.openSession()) {
            EmployeeDao employeeDao = session.getMapper(EmployeeDao.class);
            Employee employee = employeeDao.selectEmployeeById(empId);

            if (employee != null) {
                displayEmployeeDetail(employee);
            } else {
                System.out.println("员工不存在！");
            }
        } catch (Exception e) {
            System.err.println("查询员工失败：" + e.getMessage());
        }
    }

    // 查询所有员工
    private static void listAllEmployees() {
        System.out.println("\n--- 所有员工列表 ---");

        try (SqlSession session = sqlSessionFactory.openSession()) {
            EmployeeDao employeeDao = session.getMapper(EmployeeDao.class);
            List<Employee> employees = employeeDao.selectAllEmployees();

            if (employees.isEmpty()) {
                System.out.println("暂无员工数据！");
            } else {
                System.out.println("共 " + employees.size() + " 名员工：");
                for (int i = 0; i < employees.size(); i++) {
                    System.out.println((i + 1) + ". " + employees.get(i));
                }
            }
        } catch (Exception e) {
            System.err.println("查询员工列表失败：" + e.getMessage());
        }
    }

    // 条件查询
    private static void queryEmployeesByCondition() {
        System.out.println("\n--- 条件查询 ---");

        Map<String, Object> condition = new HashMap<>();

        String empName = getStringInput("姓名（可选）：");
        if (!empName.isEmpty()) condition.put("empName", empName);

        String department = getStringInput("部门（可选）：");
        if (!department.isEmpty()) condition.put("department", department);

        String position = getStringInput("职位（可选）：");
        if (!position.isEmpty()) condition.put("position", position);

        String minSalary = getStringInput("最低薪资（可选）：");
        if (!minSalary.isEmpty()) condition.put("minSalary", Double.parseDouble(minSalary));

        String maxSalary = getStringInput("最高薪资（可选）：");
        if (!maxSalary.isEmpty()) condition.put("maxSalary", Double.parseDouble(maxSalary));

        try (SqlSession session = sqlSessionFactory.openSession()) {
            EmployeeDao employeeDao = session.getMapper(EmployeeDao.class);
            List<Employee> employees = session.selectList(
                    "com.factory.dao.EmployeeDao.selectEmployeesByCondition", condition);

            if (employees.isEmpty()) {
                System.out.println("未找到符合条件的员工！");
            } else {
                System.out.println("找到 " + employees.size() + " 名符合条件的员工：");
                for (int i = 0; i < employees.size(); i++) {
                    System.out.println((i + 1) + ". " + employees.get(i));
                }
            }
        } catch (Exception e) {
            System.err.println("条件查询失败：" + e.getMessage());
        }
    }

    // 统计信息
    private static void showStatistics() {
        System.out.println("\n--- 统计信息 ---");

        try (SqlSession session = sqlSessionFactory.openSession()) {
            EmployeeDao employeeDao = session.getMapper(EmployeeDao.class);

            // 部门统计
            List<Map<String, Object>> deptStats = session.selectList(
                    "com.factory.dao.EmployeeDao.selectDepartmentStats");

            System.out.println("\n部门统计：");
            for (Map<String, Object> stat : deptStats) {
                System.out.printf("部门: %-10s 人数: %-3d 平均薪资: %-8.2f 最高薪资: %-8.2f 最低薪资: %-8.2f\n",
                        stat.get("department"), stat.get("employee_count"),
                        stat.get("avg_salary"), stat.get("max_salary"), stat.get("min_salary"));
            }

            // 薪资分布
            List<Map<String, Object>> salaryDist = session.selectList(
                    "com.factory.dao.EmployeeDao.selectSalaryDistribution");

            System.out.println("\n5薪资分布：");
            for (Map<String, Object> dist : salaryDist) {
                System.out.printf("薪资范围: %-10s 人数: %d\n",
                        dist.get("salary_range"), dist.get("count"));
            }

        } catch (Exception e) {
            System.err.println("统计信息失败：" + e.getMessage());
        }
    }

    // 显示员工详细信息
    private static void displayEmployeeDetail(Employee employee) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println("\n=== 员工详细信息 ===");
        System.out.println("员工ID: " + employee.getEmpId());
        System.out.println("姓名: " + employee.getEmpName());
        System.out.println("性别: " + ("M".equals(employee.getGender()) ? "男" : "女"));
        System.out.println("年龄: " + employee.getAge());
        System.out.println("职位: " + employee.getPosition());
        System.out.println("部门: " + employee.getDepartment());
        System.out.println("薪资: " + employee.getSalary());
        System.out.println("入职日期: " + (employee.getHireDate() != null ? sdf.format(employee.getHireDate()) : ""));
        System.out.println("邮箱: " + employee.getEmail());
        System.out.println("电话: " + employee.getPhone());
        System.out.println("地址: " + employee.getAddress());
        System.out.println("创建时间: " + (employee.getCreateTime() != null ? sdf.format(employee.getCreateTime()) : ""));
    }

    // 工具方法
    private static String getStringInput(String prompt) {
        System.out.print(prompt);
        return scanner.nextLine().trim();
    }

    private static int getIntInput(String prompt) {
        while (true) {
            try {
                System.out.print(prompt);
                return Integer.parseInt(scanner.nextLine().trim());
            } catch (NumberFormatException e) {
                System.out.println("请输入有效的数字！");
            }
        }
    }

    private static double getDoubleInput(String prompt) {
        while (true) {
            try {
                System.out.print(prompt);
                return Double.parseDouble(scanner.nextLine().trim());
            } catch (NumberFormatException e) {
                System.out.println("请输入有效的数字！");
            }
        }
    }
}